package com.wandousoushu.jiusen.ui.bookshelf

import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.wandousoushu.jiusen.MyApplication
import com.wandousoushu.jiusen.MyApplication.Companion.instance
import com.wandousoushu.jiusen.R
import com.wandousoushu.jiusen.adapter.BookShelfAdapter
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.model.BookManager
import com.wandousoushu.jiusen.help.IntentDataHelp
import com.wandousoushu.jiusen.lib.dialogs.alert
import com.wandousoushu.jiusen.ui.book.read.ReadBookActivity
import com.wandousoushu.jiusen.ui.book.read.ReadOriginActivity
import com.wandousoushu.jiusen.ui.info.BookInfoActivity
import com.wandousoushu.jiusen.ui.search.SearchActivity
import com.wandousoushu.jiusen.util.*
import com.wandousoushu.jiusen.web.http.MainHttpUtils
import com.wandousoushu.jiusen.lib.dialogs.alert
import com.wandousoushu.jiusen.lib.dialogs.noButton
import com.wandousoushu.jiusen.lib.dialogs.okButton
import com.wandousoushu.jiusen.ui.login.LoginActivity
import kotlinx.android.synthetic.main.fragment_bookshelf.*
import org.jetbrains.anko.sdk27.listeners.onClick
import org.jetbrains.anko.startActivity
import org.jetbrains.anko.toast
import org.json.JSONArray
import org.json.JSONObject


class BookShelfFragment : Fragment() {
    private var searchImageView: ImageView? = null
    private var bookShelfRecycerView: RecyclerView? = null
    private var addTextView: TextView? = null
    private var noneLinearLayout: LinearLayout? = null
    var adapter: BookShelfAdapter? = null
    var deleteTextView: TextView? = null
    var managerImageView: ImageView? = null
    var isSelect = false

    override fun onCreateView(inflater: LayoutInflater,
                              container: ViewGroup?, savedInstanceState: Bundle?): View? {
        val root = inflater.inflate(R.layout.fragment_bookshelf, container, false)
        searchImageView = root.findViewById<View>(R.id.bookshelf_iv_search) as ImageView
        searchImageView!!.setOnClickListener {
            val intent = Intent(requireContext(), SearchActivity::class.java)
            startActivity(intent)
        }
        bookShelfRecycerView = root.findViewById<View>(R.id.bookshelf_recycerview) as RecyclerView
        //纵向线性布局
        val layoutManager = GridLayoutManager(requireContext(), 3)
        bookShelfRecycerView!!.layoutManager = layoutManager
        addTextView = root.findViewById(R.id.bookshelf_add)
        addTextView!!.onClick {
            if (MyApplication.instance.isLogin) {
                val intent = Intent(requireContext(), SearchActivity::class.java)
                startActivity(intent)
            } else {
                startActivity<LoginActivity>()
            }
        }
        noneLinearLayout = root.findViewById(R.id.bookshelf_ll_none)
        deleteTextView = root.findViewById(R.id.bookshelf_btn_delete)
        deleteTextView!!.onClick {
            if (adapter!!.GetSelectList().size == 0) {
                toast(R.string.del_select_tip)
            } else {
                alert(title = getString(R.string.sure_del)) {
                    message = getString(R.string.sure_del_select_book)
                    okButton {
                        mHandle.sendEmptyMessage(3)
                    }
                    noButton {

                    }
                }.show().applyTint()
            }
        }
        managerImageView = root.findViewById(R.id.bookshelf_iv_manager)
        managerImageView!!.onClick {
            isSelect = !isSelect
            adapter!!.setStartSelect(isSelect)
            if (isSelect) {
                deleteTextView!!.setText(getString(R.string.bookshelf_select_format, adapter!!.GetSelectList().size))
                deleteTextView!!.visible()
            } else {
                deleteTextView!!.gone()
            }
        }
        InitData()
        return root
    }

    private fun InitData() {
        if (MyApplication.instance.isLogin) {
            HttpGetBookShelf()
        }
    }

    override fun onResume() {
        super.onResume()
        mHandle.sendEmptyMessage(0)
    }

    private fun HttpGetBookShelf() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBooks(2, instance.token)
                        ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject != null && jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val jObject = JSONObject(data)
                    val lists = jObject.getString("lists")
                    val jsonArray = JSONArray(lists)
                    for (i in 0 until jsonArray.length()) {
                        val json = jsonArray[i] as JSONObject
                        val book = Book()
                        book.name = json.getString("name")
                        book.bookUrl = json.getString("url")
                        book.tocUrl = json.getString("chapter_url")
                        book.latestChapterTitle = json.getString("final_refresh_data")
                        book.coverUrl = json.getString("cover_url")
                        book.author = json.getString("author")
                        book.intro = json.getString("introduce")
                        book.origin = json.getString("origin")
                        book.originName = json.getString("origin_name")
                        book.charset = json.getString("charset")
                        book.group = 2
                        book.durChapterTitle = json.getString("dur_chapter_title")
                        book.durChapterIndex = json.getInt("dur_chapter_index")
                        book.durChapterPos = json.getInt("dur_chapter_pos")
                        book.order = i
                        BookManager.GetInstance().AddBook(book)
                    }
                    mHandle.sendEmptyMessage(0)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private val mHandle: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0 -> {
                    deleteTextView!!.gone()
                    isSelect = false
                    var bookList = BookManager.GetInstance().GetBookListByType(2)
                    if (bookList.size == 0) {
                        bookShelfRecycerView!!.gone()
                        noneLinearLayout!!.visible()
                    } else {
                        noneLinearLayout!!.gone()
                        bookShelfRecycerView!!.visible()
                    }
                    adapter = BookShelfAdapter(requireContext(), bookList)
                    adapter!!.setActionListener { book ->
                        startActivity<ReadBookActivity>(
                                Pair("inBookshelf", true),
                                Pair("bookUrl", book.bookUrl),
                                Pair("key", IntentDataHelp.putData(book))
                        )
                    }
                    adapter!!.setLongClickListener {
                        startActivity<BookInfoActivity>(
                                Pair("name", it.name),
                                Pair("author", it.author),
                        )
                    }
                    adapter!!.setCheckedListener() {
                        deleteTextView!!.setText(getString(R.string.bookshelf_select_format, it.size))
                    }
                    bookShelfRecycerView!!.adapter = adapter
                }
                1 -> Toast.makeText(requireContext(), resources.getString(R.string.bookshelf_http_fail), Toast.LENGTH_SHORT).show()
                2 -> Toast.makeText(requireContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show()
                3 -> {
                    Thread(Runnable {
                        BookManager.GetInstance().RemoveBookShelfs(adapter!!.GetSelectList(), 2)
                        sendEmptyMessage(4)
                        sendEmptyMessage(0)
                    }).start()
                }
                4 ->toast(R.string.del_success)

            }
        }
    }
}